package com.example.mlm;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.pojos.Product;
import com.example.pojos.Product_Type;
import com.example.tools.XMLTools;

public class MainActivity extends ListActivity implements OnItemClickListener{
	private ListView listView;
	private String[] values;
	private HashMap<Product_Type, ArrayList<Product>> products = null;
	private ProgressDialog pd;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        values = getResources().getStringArray(R.array.marketType);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
        
        listView = getListView();
        listView.setOnItemClickListener(this);
        
        deSerializeMap();
        if(products == null) { 
        	Log.e("application","n'a rien gette");
        	pd = ProgressDialog.show(this, "progress", "wait until loading...");
        	new Async().execute();
        }
        else{
        	Log.e("application","n'a rien recharge");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.refresh:
	        	pd = ProgressDialog.show(this, "progress", "wait until loading...");
	        	new Async().execute();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
    
    @Override
	public void onItemClick(AdapterView<?> parent, View view,
	    int position, long id) {
		  Intent intent = new Intent(this, AfficheProduit.class);
		  Log.e("position", position+"");
		  switch (position) {
			case 0:
				intent.putParcelableArrayListExtra("products", products.get(Product_Type.MUSIQUE));
				intent.putExtra("isPanier", false);
				break;
			case 1:
				intent.putParcelableArrayListExtra("products", products.get(Product_Type.VIDEO));
				intent.putExtra("isPanier", false);
				break;
			case 2:
				intent.putParcelableArrayListExtra("products", products.get(Product_Type.IMAGE));
				intent.putExtra("isPanier", false);
				break;
			case 3:
				intent.putParcelableArrayListExtra("products", products.get(Product_Type.DEVICE));
				intent.putExtra("isPanier", false);
				break;
			case 4:
				intent.putExtra("isPanier", true);
				break;
				//intent.putParcelableArrayListExtra("products", products.get(Product_Type.DEVICE));
			default:
				return;
		  }
		  
		  startActivity(intent);
    	
	} 
    
    @Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putParcelableArrayList(Product_Type.DEVICE.name(), products.get(Product_Type.DEVICE));
		outState.putParcelableArrayList(Product_Type.VIDEO.name(), products.get(Product_Type.VIDEO));
		outState.putParcelableArrayList(Product_Type.IMAGE.name(), products.get(Product_Type.IMAGE));
		outState.putParcelableArrayList(Product_Type.MUSIQUE.name(), products.get(Product_Type.MUSIQUE));
	}
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	ArrayList<Product> devices = savedInstanceState.getParcelableArrayList(Product_Type.DEVICE.name());
    	products.put(Product_Type.DEVICE, devices);
    	
    	ArrayList<Product> images = savedInstanceState.getParcelableArrayList(Product_Type.IMAGE.name());
    	products.put(Product_Type.IMAGE, images);
    	
    	ArrayList<Product> videos = savedInstanceState.getParcelableArrayList(Product_Type.VIDEO.name());
    	products.put(Product_Type.VIDEO, videos);
    	
    	ArrayList<Product> musiques = savedInstanceState.getParcelableArrayList(Product_Type.MUSIQUE.name());
    	products.put(Product_Type.MUSIQUE, musiques);
    }
    
    private class Async extends AsyncTask<Void, Integer, Void> {
    	private XMLTools xmlReader;
    	
    	@Override
    	protected void onPreExecute() {
    		super.onPreExecute();
    		xmlReader = new XMLTools();
    		Log.i("appli", "onPreExecute");
    	}
    	
    	@Override
    	protected Void doInBackground(Void... params) {
    		Log.i("appli", "on working");
    		products = xmlReader.getFeeds();
    		
    		Log.e("application","a eu les products");
			return null;
    	}
    	
    	@Override
    	protected void onPostExecute(Void result) {
    		super.onPostExecute(result);
    		serializeMap();
    		pd.dismiss();
    		//canClick = true;
    	}

    }
    
    @SuppressWarnings("unchecked")
	public void deSerializeMap(){
    	try {
            FileInputStream fStream = openFileInput("products.bin") ;
            ObjectInputStream oStream = new ObjectInputStream(fStream);

            products = (HashMap<Product_Type, ArrayList<Product>>) oStream.readObject();        
            oStream.close();

            Log.e("deSerialization success", "Success");
        } catch (Exception e) {
            Log.e("IO Exception", e.getMessage());
        }
    }
    public void serializeMap() {
        try {
            FileOutputStream fStream = openFileOutput("products.bin", Context.MODE_PRIVATE) ;
            ObjectOutputStream oStream = new ObjectOutputStream(fStream);

            oStream.writeObject(products);        
            oStream.flush();
            oStream.close();

            Log.e("Serialization success", "Success");
        } catch (Exception e) {
            Log.e("IO Exception", e.getMessage());
        }
    }   
    
}
